package group.igfd.manager.biz.controller;

import java.util.*;

import com.alibaba.fastjson.JSON;
import group.igfd.manager.biz.entity.*;
import group.igfd.manager.biz.model.PublishBuyerAddModel;
import group.igfd.manager.biz.service.*;
import group.igfd.manager.biz.utils.ImageUtils;
import group.igfd.manager.biz.utils.JedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * buyer发布表
 *
 * @author knight
 * @email sunlightcs@gmail.com
 * @date 2018-10-17 15:59:19
 */
@RestController
@RequestMapping("biz/publishbuyers")
@Api(tags = {"A005/ 买手发布商品管理"})
public class PublishBuyersController {

    private Logger logger = LoggerFactory.getLogger(PublishBuyersController.class);

    @Autowired
    private PublishBuyersService publishBuyersService;

    @Autowired
    private TagHotPublishService tagHotPublishService;

    @Autowired
    private TagStylePublishService tagStylePublishService;

    @Autowired
    private SyncEsListService syncEsListService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("biz:publishbuyers:list")
    public R list(@RequestParam Map<String, Object> params) {
        logger.info("biz:publishbuyers:list=== params:[{}]", JSON.toJSONString(params));
        PageUtils page = publishBuyersService.queryPage(params);

        logger.info("biz:publishbuyers:list==='s response: [{}]", JSON.toJSONString(page));
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("biz:publishbuyers:info")
    public R info(@PathVariable("id") Integer id) {
        PublishBuyersEntity publishBuyers = publishBuyersService.selectById(id);

        return R.ok().put("publishBuyers", publishBuyers);
    }

    /**
     * 保存
     */
    @PostMapping(value = "/save")
    @RequiresPermissions("biz:publishbuyers:save")
    @ApiOperation(value = "买手发布商品")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody PublishBuyerAddModel model) {

        logger.info("biz:publishbuyers:save=== model:[{}]", JSON.toJSONString(model));
        PublishBuyersEntity entity = new PublishBuyersEntity();
        entity.setTitlePicture(model.getTitlePic());
        String[] descArr = model.getDetailDesc();
        if (null != descArr && descArr.length > 0) {
            List<Map<String, String>> list = new ArrayList<>(descArr.length);

            Map<String, String> mapTitle = new HashMap<>();
            Integer[] imageInfoTitle = ImageUtils.getImagesWidthAndHight(model.getTitlePic());

            mapTitle.put("imageWidth", String.valueOf(imageInfoTitle[0]));
            mapTitle.put("imageHeight", String.valueOf(imageInfoTitle[1]));
            mapTitle.put("type", "image");
            mapTitle.put("imageURL", model.getTitlePic());
            list.add(mapTitle);

            for (int i = 0; i < descArr.length; i++) {
                Map<String, String> map = new HashMap<>();

                Integer[] imageInfo = ImageUtils.getImagesWidthAndHight(descArr[i]);

                map.put("imageWidth", String.valueOf(imageInfo[0]));
                map.put("imageHeight", String.valueOf(imageInfo[1]));
                map.put("type", "image");
                map.put("imageURL", descArr[i]);
                list.add(map);
            }
            entity.setDescJson(JSON.toJSONString(list));
        }
        entity.setUid(model.getUid());
        entity.setTitle(model.getTitle());
        entity.setBrand(model.getBrandId());
        entity.setType(model.getCategoryId());
        entity.setSex(model.getSex());
        entity.setEurPrice(Double.parseDouble(model.getPrice()));
        entity.setDay(Integer.valueOf(model.getArrivalTime()));
        entity.setSku(model.getSku());
        entity.setColor(model.getColor());
        entity.setSize(model.getSize());
        entity.setLocation(model.getLocation());
        entity.setCreatedAt(new Date());
        entity.setUpdatedAt(new Date());
        entity.setDiscount(model.getDiscount());
        publishBuyersService.insert(entity);

        //添加商品热门、风格标签
        List<TagHotPublishEntity> tagHotPublishEntityList = new ArrayList<TagHotPublishEntity>();
        List<TagStylePublishEntity> tagStylePublishEntityList = new ArrayList<TagStylePublishEntity>();
        for (String tagHost : model.getTagHotId()) {
            TagHotPublishEntity tagHotPublishEntity = new TagHotPublishEntity();
            tagHotPublishEntity.setPublishId(entity.getId());
            tagHotPublishEntity.setTagHotId(Integer.valueOf(tagHost));
            tagHotPublishEntity.setType("buyer");
            tagHotPublishEntityList.add(tagHotPublishEntity);
        }
        for (String tagStyle : model.getTagStyleId()) {
            TagStylePublishEntity tagStylePublishEntity = new TagStylePublishEntity();
            tagStylePublishEntity.setPublishId(entity.getId());
            tagStylePublishEntity.setTagStyleId(Integer.valueOf(tagStyle));
            tagStylePublishEntity.setType("buyer");
            tagStylePublishEntityList.add(tagStylePublishEntity);
        }
        if (tagHotPublishEntityList.size() > 0) {
            tagHotPublishService.insertBatch(tagHotPublishEntityList);
        }
        if (tagStylePublishEntityList.size() > 0) {
            tagStylePublishService.insertBatch(tagStylePublishEntityList);
        }
        logger.info("biz:publishbuyers:save====OK");

        //添加同步Es记录
        SyncEsListEntity syncEsListEntity = new SyncEsListEntity();
        syncEsListEntity.setPublishId(String.valueOf(entity.getId()));
        syncEsListEntity.setFlushType("product");
        syncEsListEntity.setType("insert");
        syncEsListService.insert(syncEsListEntity);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("biz:publishbuyers:update")
    public R update(@RequestBody PublishBuyersEntity publishBuyers) {
        publishBuyersService.updateById(publishBuyers);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("biz:publishbuyers:delete")
    public R delete(@RequestBody Integer[] ids) {
//		publishBuyersService.deleteBatchIds(Arrays.asList(ids));
        List<PublishBuyersEntity> list = publishBuyersService.selectBatchIds(Arrays.asList(ids));
        list.stream().forEach(entity -> entity.setDeletedAt(new Date()));
        publishBuyersService.updateBatchById(list, 20);

        List<SyncEsListEntity> syncEsListEntities = new ArrayList<>();
        //添加同步Es记录
        for (Integer id:ids) {
            SyncEsListEntity syncEsListEntity = new SyncEsListEntity();
            syncEsListEntity.setPublishId(String.valueOf(id));
            syncEsListEntity.setFlushType("product");
            syncEsListEntity.setType("delete");
            syncEsListService.insert(syncEsListEntity);
        }

        return R.ok();
    }

}
